/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.lct.eq2.backup;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Me
 */
public class MulticastServerThread extends Thread {
    private boolean open;
    Socket socket;
    MulticastServer parent;
    
    public MulticastServerThread() {
    }
    
    public MulticastServerThread(Socket sock, MulticastServer parent) {
        this.parent = parent;
        //System.out.println("MulticastServerThread::socket port = " + sock.getPort());
        this.open = true;
        this.socket = sock;
    }
    
    public void closeSocket() {
        this.open = false;
    }
    
    @Override
    public void run() {
        ObjectInputStream is = null;
        try {
            is = new ObjectInputStream(this.socket.getInputStream());
            Object o = is.readObject();
            String className = o.getClass().getName();
            if (className.equalsIgnoreCase("java.lang.String")) {
                String classData = o.toString();
                if (classData.indexOf("::") > 0) {
                    this.parent.removeServer(o.toString().substring(classData.indexOf("::") + 2));
                    System.out.println("MulticastServerThread::Removed server: " + o.toString().substring(classData.indexOf("::") + 2));
                } else {
                    this.parent.addServer(classData);
                    System.out.println("MulticastServerThread::Added server: " + classData);
                }
            } else {
                this.parent.sendData(o);
            }
            //System.out.println(o.getClass().getName());
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(MulticastServerThread.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(MulticastServerThread.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                is.close();
            } catch (IOException ex) {
                Logger.getLogger(MulticastServerThread.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        
    }
}
